<template>
  <div class="container">
    <div v-if="showContent === 1" class="loading">
      <!-- 加载中, 请稍后 {{ showContent }} -->
    </div>
    <div v-if="showContent === 2" class="login-form">
      <h3 style="text-align: center;">仁相华龙智慧屏</h3>
      <van-form @submit="onSubmit">
        <van-field
          v-model="formData.publicSecurityCode"
          name="publicSecurityCode"
          label="公安编码"
          maxlength="50"
          placeholder="公安编码"
          :rules="[{ required: true, message: '请填写公安编码' }]"
        />
        <van-field
          v-model="formData.localPoliceStation"
          is-link
          readonly
          name="localPoliceStation"
          label="所属派出所"
          placeholder="所属派出所"
          :rules="[{ required: true, message: '请填写所属派出所' }]"
          @click="showSelect = true"
        />
          <van-popup v-model="showSelect" round position="bottom">
            <van-cascader
              v-model="selectValue"
              title="请选择所属派出所"
              :options="options"
              @close="showSelect = false"
              @finish="onFinish"
            />
          </van-popup>
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
    <div v-if="showContent === 3" class="silder">
      <div class="silder-header">
        <div class="holet-name">{{ publicSecurityCode }}</div>
        <div v-if="showCheckoutMode" class="checkmode">
          <van-field v-model="mode2password" type="password" label="运营密码" style="width: 300px" placeholder="请输入运营密码" />
          <van-button type="primary" @click="handleCheckoutMode2" style="width: 140px">确定</van-button>
          <van-button @click="showCheckoutMode = false" style="width: 140px">取消</van-button>
        </div>
        <div class="app-time">
          {{ time }}
          <div class="checkout-mode" :class="'mode' + mode" @click="onCheckoutMode">切换至日常模式</div>
        </div>
      </div>
      <div class="silder-content" :style="{height: innerHeight > 0 ? innerHeight - 60 + 'px' : 'calc(100vh - 60px)'}">
        <div v-if="!pages || !pages.length">
          <img src="@/assets/welcome.png" alt="" class="welcome" :style="{height: innerHeight > 0 ? innerHeight - 60 + 'px' : 'calc(100vh - 60px)'}">
        </div>
        <van-swipe class="my-swipe" ref="swipe" :loop="true" :touchable="false" :duration="10" :show-indicators="false" @change="onChangeSwipe">
          <van-swipe-item v-for="(item, i) in pages" :key="item.id">
            <img v-if="item.type === 1" :src="item.content || item.src" alt="" class="swipe-item-nr" :style="{height: innerHeight > 0 ? innerHeight - 60 + 'px' : 'calc(100vh - 60px)'}">
            <div v-if="item.type === 2" class="swipe-item-nr swipe-item-videobg">
              <!-- {{item.id}} -->
              <img v-if="setUrl(i)" :src="setUrl(i)" alt="" class="swipe-item-nr" :style="{height: innerHeight > 0 ? innerHeight - 60 + 'px' : 'calc(100vh - 60px)'}">
            </div>
          </van-swipe-item>
        </van-swipe>
      </div>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import { getUrlParam, guid } from '@/utils'
import { PoliceStation } from '@/configs/data'
let downcountinfo, modecheckouttimeout, swipetimeout, page3timeout, refreshtimeout, resultDataTimeout, inittimeout
function connectWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) {
      callback(WebViewJavascriptBridge)
  } else {
      document.addEventListener(
          'WebViewJavascriptBridgeReady'
          , function() {
              callback(WebViewJavascriptBridge)
          },
          false
      );
  }
}
export default {
  data() {
    return {
      debug: this.$route.query.debug,
      sn: '',
      ip: '',
      lat: '',
      lon: '',
      showContent: 1,  // 1 稍后   2 登录  3 轮播

      formData: {
        hotelName: '',
        name: '',
        phone: '',
      },
      publicSecurityCode: '',
      showtime: 20, // 默认的轮播间隔时间 单位s
      time: moment().format('YYYY-MM-DD HH:mm:ss'),
      pagesStr: '',
      pages: [],
      swiperSelected: 0,

      showSelect: false,
      selectValue: '',
      options: PoliceStation,
      
      showCheckoutMode: false,
      mode: 2, // 1运营模式  2 使用模式
      checkoutmode: 0,
      mode2password: '',

      innerHeight: 0,

      resultDataNum: 0,
    };
  },
  watch: {
    resultDataNum(val) {
      if (val === 10) {
        clearInterval(resultDataTimeout)
        this.pages = this.pagesStr ? JSON.parse(this.pagesStr) : []
        this.page3Init()
      }
    }
  },

  created() {
    setTimeout(() => {
      this.setDisconnectHtmlUrl()
    }, 60 * 1000)

    setInterval(() => { // 更新右上角时间
      this.time = moment().format('YYYY-MM-DD HH:mm:ss')
    }, 1000)

    clearInterval(refreshtimeout)
    refreshtimeout = setInterval(() => { // 定时更新页面内容
      this.refresh()
    }, 12 * 60 * 60 * 1000)

    const that = this
    const storageSn = localStorage.getItem('sn')
    if (this.debug) {
      this.sn = this.$route.query.sn || storageSn || guid()
      localStorage.setItem('sn', this.sn)
      this.startInit()
    }

    if (storageSn) {
      this.sn = storageSn
      that.startInit()
    } 
    connectWebViewJavascriptBridge(function(bridge) {
      bridge.init(function(message, responseCallback) {
        responseCallback();
      });

      bridge.registerHandler("state", function(data, responseCallback) {
        if (data === 'web_loaded') {
        } else if (data === 'video_play_finished') {
          that.onVideoEnded()
          responseCallback(true);
        }
      });
      bridge.registerHandler("receiveParamFromAndroid", function (data, callback){
        const info = JSON.parse(data)
        if (info && info.sn) {
          that.sn = info.sn
          // that.sn = localStorage.getItem('sn') || guid()
          localStorage.setItem('sn', that.sn)
          that.ip = info.ip
          that.lat = info.lat
          that.lon = info.lon
          that.startInit()
        }
      })

      bridge.registerHandler("resultData", function(data, responseCallback) {
        if (data) {
          // that.pages = JSON.parse(data)
          that.page3Init()
        } else {
          this.resultDataNum = 10
        }
        clearInterval(resultDataTimeout)
      });
    })
    
    this.$nextTick(() => {
      this.innerHeight = window.innerHeight
    })
  },

  methods: {
    startInit() {
      const { sn } = this
      if (sn) {
        this.resultDataNum = 0
        this.$http.get(`/banner/all/sn/${sn}`).then(res => {
          if (res.data) {
            const { pages = [], publicSecurityCode, time } = res.data
            this.showContent = 3
            this.publicSecurityCode = publicSecurityCode
            this.pages = pages
            this.pagesStr = pages && pages.length ? JSON.stringify(pages) : ''
            this.postDataToAndroid(this.pagesStr)
            this.showtime = time
            this.handleUpdateDeviceStatus()
          } else {
            this.showContent = 2
          }
        }).catch(err => {
          if (err == 'Error: Network Error') {
            this.refresh()
          }
        })
      }

      clearTimeout(inittimeout)
      inittimeout = setTimeout(() => { // 轮询请求一次最新的下发数据
        this.startInit()
      }, 10 * 60 * 1000)
    },

    page3Init() {
      const firstItem = this.pages[this.swiperSelected] || {}
      console.log('firstItem.type', firstItem.type, firstItem.type === 1)
      if (firstItem.type === 1) {
        this.onStartDowncount()
      } else {
        this.onChangeSwipe(0)
      }
    },

    handleUpdateDeviceStatus() { // 3分钟更新一次设备的状态
      this.$http.put(`/device/sn/${this.sn}`)
      setTimeout(() => {
        this.handleUpdateDeviceStatus()
      }, 3 * 60 * 1000)
    },

    onSubmit(values) {
      const { sn, ip, lat, lon } = this
      const data = {
        ...values,
        sn, ip,
        longitude: lon || 104.5,
        latitude: lat || 30.5
      }
      this.$http.post('/device/add', data).then(res => {
        this.showContent = 3
        this.startInit()
      }).catch(err => {
        this.$dialog.alert({
          message: JSON.stringify(err)
        })
      })
    },

    onChangeSwipe(i) {
      this.swiperSelected = i
      const pageItem = this.pages[i] || {}
      if (pageItem.type === 2) {
        clearTimeout(swipetimeout)
        this.handleAndriodPlayVideo(pageItem.src)
      } else if (pageItem.type === 1) {
        this.onStartDowncount()
      }
    },
    toNext() {
      if(this.pages.length > 1) {
        this.$refs.swipe && this.$refs.swipe.next()
      } else {
        this.onChangeSwipe(0)
      }
    },
    onStartDowncount() {
      clearTimeout(swipetimeout)
      swipetimeout = setTimeout(() => {
        this.toNext()
      }, this.showtime * 1000)
    },
    onVideoEnded() { // 视频播放结束
      this.toNext()
    },
    // 让android播放视频
    handleAndriodPlayVideo(url) {
      if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.callHandler) {
        window.WebViewJavascriptBridge.callHandler('videoViewLocation', { url, top: 58, left: 0, right: -1, bottom: -1 }, (responseData) =>  {
          console.log('responseData', responseData)
        })
      } else {
        setTimeout(() => {
          this.onVideoEnded()
        }, 3000)
      }
      
    },

    onFinish({ selectedOptions }) {
      this.showSelect = false
      let text = ''
      selectedOptions.forEach(n => {
        text += n.text
      });
      this.formData.localPoliceStation = text
    },

    onCheckoutMode() {
      if (this.mode === 1) {
        this.mode = 2
        this.changeAutoRestartApp(true)
      } else if (this.mode === 2){
        if (this.checkoutmode > 0) {
          this.showCheckoutMode = true
        } else {
          this.checkoutmode++
          clearTimeout(modecheckouttimeout)
          modecheckouttimeout = setTimeout(() => {
            this.checkoutmode = 0
          }, 500)
        }
      }
    },
    handleCheckoutMode2() {
      this.showCheckoutMode = false
      if (this.mode2password === 'qqq') {
        this.mode = 1
        this.changeAutoRestartApp(false)
      }
      this.mode2password = ''
    },
    changeAutoRestartApp(isAutoRestart) {
      if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.callHandler) {
        window.WebViewJavascriptBridge.callHandler('autoRestartApp', { isAutoRestart })
      }
    },

    refresh() {
      if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.callHandler) {
        window.WebViewJavascriptBridge.callHandler('reloadPage')
      }
    },

    postDataToAndroid(data) {
      if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.callHandler) {
        if (this.resultDataNum < 10) {
          clearInterval(resultDataTimeout)
          resultDataTimeout = setInterval(() => {
            if (this.resultDataNum < 10) {
              this.resultDataNum++
            }
          }, 1000)
        }
        window.WebViewJavascriptBridge.callHandler('dataSource', data)
      } else {
        this.resultDataNum = 10
      }
    },

    setDisconnectHtmlUrl() { // 设置离线地址
      if (window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.callHandler) {
        window.WebViewJavascriptBridge.callHandler('setDisconnectHtmlUrl', {
          host:"https://www.dayuanxinxi.com/jdp",
          path:[
            "index.html",
            "js/app.822dec73.js",
            "js/chunk-98dbf4a0.dea1c217.js",
            "js/chunk-vendors.949e7f7d.js",
            "css/app.6e7edf97.css",
            "css/chunk-98dbf4a0.d1cf3c98.css",
            "css/chunk-vendors.f10ea90a.css"
          ]
        })
      }
    },

    setUrl(i) {
      if (i < this.pages.length - 1) {
        const item = this.pages[i + 1]
        if (item.type === 1) {
          return item.content || item.src
        }
      } else {
        const item = this.pages[0]
        if (item.type === 1) {
          return item.content || item.src
        }
      }
    },
  }
};
</script>
<style lang="less" scoped>
.container {
  height: 100vh;
  background: #f5f5f5;
  font-size: 0.14rem;
  line-height: 0.2rem;
  color: #333;
  .loading{
    width: 100vw;
    height: 100vh;
    background: #fafafa;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: .3rem;
    color: #333;

    position: fixed;
    top: 0;
    left: 0;
    z-index: 6;
  }

  .login-form{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 5;
    width: 100vw;
    height: 100vh;
    background: #fff;
  }

  .silder{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 4;
    width: 100vw;
    height: 100vh;
    background: #fafafa;
    .silder-header{
      position: relative;
      height: 60px;
      background: #096dd9;
      width: 100vw;
      color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 .12rem;
      box-sizing: border-box;
      font-size: .13rem;
    }
    .app-time{
      position: relative;
    }
    .envdev{
      font-size: 14px;
    }
    .checkout-mode{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      opacity: 0;
      z-index: 2;
      &.mode1{
        opacity: 1;
        left: -100%;
        right: 100%;
      }
    }

    .silder-content{
      width: 100vw;
      height: calc(100vh - 60px);
      .my-swipe{
        width: 100%;
        height: 100%;
      }
      .swipe-item-nr{
        width: 100%;
        height: 100%;
      }
      .swipe-item-videobg{
        background: #000;
      }
    }
  }

  .checkmode{
    display: flex;
    position: absolute;
    left: 20%;
    top: 8px;
    z-index: 2;
  }

  .welcome{
    display: block;
    width: 100vw;
    height: calc(100vh - 60px);
  }
  .welcome-text{
    position: absolute;
    left: 10px;
    top: 100px;
    z-index: 2;
  }
}
* {
  box-sizing: border-box;
}
</style>
